package com.qiandw.security.handle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qiandw.security.entity.UserDetailImpl;
import com.qiandw.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler;
import reactor.core.publisher.Mono;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author coxx
 */
@Slf4j
public class ServerLoginSuccessHandle extends RedirectServerAuthenticationSuccessHandler {

    private DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        User userDetails = ((User) authentication.getPrincipal());
        log.info(String.format("用户：%1$s, 权限列表：%2$s, 登陆时间：%3$s, 登陆IP：%4$s", userDetails.getUsername(), JSON.toJSONString(userDetails.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()),
                SerializerFeature.NotWriteDefaultValue), dataFormat.format(new Date()), IPUtils.getIPAddress(webFilterExchange.getExchange().getRequest())));
        return super.onAuthenticationSuccess(webFilterExchange, authentication);
    }
}
